import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { Toast } from '@douyinfe/semi-ui';

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message, data } = response.data;
    
    if (code === 200) {
      return data;
    } else if (code === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      window.location.href = '/login';
      Toast.error('登录已过期，请重新登录');
      return Promise.reject(new Error(message));
    } else {
      Toast.error(message || '请求失败');
      return Promise.reject(new Error(message));
    }
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      window.location.href = '/login';
      Toast.error('登录已过期，请重新登录');
    } else {
      Toast.error(error.message || '网络错误');
    }
    return Promise.reject(error);
  }
);

export default request;

// 通用响应类型
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
  timestamp: number;
}

// 分页响应类型
export interface PageResponse<T = any> {
  records: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

// 分页查询参数
export interface PageQuery {
  current?: number;
  size?: number;
  keyword?: string;
  orderBy?: string;
  order?: 'ASC' | 'DESC';
}